package com.wyp.service.impl;

import com.wyp.common.CodeMsg;
import com.wyp.dao.UserMapper;
import com.wyp.entity.User;
import com.wyp.exception.GlobalException;
import com.wyp.service.UserService;
import com.wyp.utils.md5.MD5Utils;
import com.wyp.utils.redis.RedisService;
import com.wyp.utils.redis.prekey.pre.UserKey;
import com.wyp.utils.uuid.UUIDUtils;
import com.wyp.vo.UserVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

/**
 * @author: Oliver
 */
@Service
public class UserServiceImpl implements UserService {
    public static final String COOKI_NAME_TOKEN = "token";
    @Autowired
    UserMapper userMapper;
    @Autowired
    RedisService redisService;

    /**
     * 对象级别缓存 使用对象级别缓存一般是常驻数据，当数据发生变化时候需要修改缓存--常见方法删除对应缓存
     * @param id
     * @return
     */
    public User getById(long id) {
        //取缓存
        User user = redisService.get(UserKey.USERKEY_BY_ID, ""+id, User.class);
        if(user != null) {
            return user;
        }
        //取数据库
        user = userMapper.selectByPrimaryKey(id);
        if(user != null) {
            redisService.set(UserKey.USERKEY_BY_ID, ""+id, user);
        }
        return user;
    }

    // http://blog.csdn.net/tTU1EvLDeLFq5btqiK/article/details/78693323
    public boolean updatePassWord(String token, long id, String formPass) {
        //取user
        User user = getById(id);
        if(user == null) {
            throw new GlobalException(CodeMsg.MOBILE_NOT_EXIST);
        }
        //更新数据库
        User toBeUpdate = new User();
        toBeUpdate.setId(id);
        toBeUpdate.setPassword(MD5Utils.formPassToDBPass(formPass, user.getSalt()));
        userMapper.updateByPrimaryKey(toBeUpdate);
        //处理缓存
        //修改缓存顺序问题：如果先修改缓存，在修改数据，当正在修改数据时候发生读操作，数据库没有修改完成，读操作读取上一个版本信息，造成数据不一致
        redisService.delete(UserKey.USERKEY_BY_ID, ""+id);
        user.setPassword(toBeUpdate.getPassword());
        //token要进行修改操作，不然会无法登陆
        redisService.set(UserKey.token, token, user);
        return true;
    }

    @Override
    public String login(HttpServletResponse response, UserVO userVO) {
        if (userVO == null) {
            throw new GlobalException(CodeMsg.SERVER_ERROR);
        }
        String mobile = userVO.getMobile();
        Long aLong = Long.valueOf(mobile);
        User user = userMapper.selectByPrimaryKey(aLong);
        if (user == null) {
            //未查找到用户
            throw new GlobalException(CodeMsg.MOBILE_NOT_EXIST);
        }
        //校验密码是否正确
        String dbSalt = user.getSalt();
        String calcPassword = MD5Utils.formPassToDBPass(userVO.getPassword(), dbSalt);
        String dbPassword = user.getPassword();
        if (!calcPassword.equals(dbPassword)) {
            //密码校验不通过
            throw new GlobalException(CodeMsg.PASSWORD_ERROR);
        }

        //获取cookie里面的token信息，根据token去数据查询一边是否已经存放了该token如果已经存放则重置失效时间。
        //登录成功之后存放session信息，实现分布式session
        String token = UUIDUtils.getUUID();
        addCookie(token, response, user);
        return token;
    }

    /**
     * 获取到token之后需要重新设置过期时间，
     *
     * @param token token
     * @return
     */
    @Override
    public User getUserByToken(String token, HttpServletResponse response) {
        if (StringUtils.isEmpty(token)) {
            return null;
        }
        User user = redisService.get(UserKey.token, token, User.class);
        if (user != null) {
            //延长有效期
            addCookie(token, response, user);
        }
        return user;
    }

    /**
     * 将信息添加到token中，并返回cookie进行记录，cookie与token具有相同的过期时间
     *
     * @param token    cookie中的token
     * @param response 写会Cookie中需要用到的response
     * @param user     用户信息
     */
    private void addCookie(String token, HttpServletResponse response, User user) {
        //将生成的token放到cookie中
        Cookie cookie = new Cookie(COOKI_NAME_TOKEN, token);
        cookie.setMaxAge(UserKey.token.expireSeconds());
        cookie.setPath("/");
        response.addCookie(cookie);
        //将token已经用户信息放入到redis中
        redisService.set(UserKey.token, token, user);
    }
}
